package com.maven.rabbitmq.rpc;

import com.maven.rabbitmq.constant.Constant;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RpcServer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1. 建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("8.135.54.49");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("study");
        connectionFactory.setPassword("study");
        connectionFactory.setVirtualHost("rabbitmq");

        Connection connection = connectionFactory.newConnection();
        //2. 创建信道
        Channel channel = connection.createChannel();

        channel.queueDeclare(Constant.RPC_QUEUE_1, true, false, false, null);

        channel.basicQos(1);
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                AMQP.BasicProperties replyProps =new AMQP.BasicProperties.Builder().
                        correlationId(properties.getCorrelationId()).
                        build();
                // 消息处理
                System.out.println("收到信息 ： " + new String(body));

                // 响应
                channel.basicPublish("", properties.getReplyTo(), replyProps,"hi I'm RPC ".getBytes());
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        channel.basicConsume(Constant.RPC_QUEUE_1,true,consumer);



    }
}
